<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed, h } from "vue";
import { ElMessage, ElMessageBox, ElTag, ElButton, ElCard } from "element-plus";
import { Refresh, VideoPlay } from "@element-plus/icons-vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  startWorkflow,
  getWorkflowStatus,
  stopWorkflow,
  getWorkflowHistory,
} from "../servers";

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);

// 工作流状态数据
const workflowStatusData = ref<any>(null);

// 工作流状态概览（根据MD文档设计）
const workflowOverview = computed(() => {
  if (!workflowStatusData.value) {
    return {
      continuous: {
        status: "unknown",
        last_check: null,
        total_processed: 0,
        workflow_id: null,
        start_time: null,
      },
      batch: { status: "idle", pending: 0 },
      verification: { status: "processing", queue: 0 },
    };
  }

  const workflows = workflowStatusData.value.workflows || {};
  return {
    continuous: {
      status: workflows.continuous?.status || "unknown",
      last_check:
        workflows.continuous?.last_processing ||
        workflows.continuous?.start_time ||
        null,
      total_processed: workflows.continuous?.total_processed || 0,
      workflow_id: workflows.continuous?.workflow_id || null,
      start_time: workflows.continuous?.start_time || null,
    },
    batch: {
      status: workflows.batch?.status || "idle",
      pending:
        workflows.batch?.pending_count || workflows.batch?.stats?.pending || 0,
      total_processed: workflows.batch?.total_processed || 0,
      workflow_id: workflows.batch?.workflow_id || null,
    },
    verification: {
      status: workflows.verification?.status || "processing",
      queue:
        workflows.verification?.queue_count ||
        workflows.verification?.stats?.queue ||
        0,
      total_processed: workflows.verification?.total_processed || 0,
      workflow_id: workflows.verification?.workflow_id || null,
    },
  };
});

// 工作流历史列表
const workflowHistoryList = ref<any[]>([]);
const historyLoading = ref(false);
const historySearchFormRef = ref<DynamicFormInstance>();

const historyPagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const historySearchForm = reactive({
  workflow_type: "",
  status: "",
  start_date: "",
  end_date: "",
});

const historySearchConfig: FormItemConfig[] = [
  {
    key: "workflow_type",
    name: "工作流类型",
    type: "select",
    labelWidth: "100px",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "批量工作流", value: "batch" },
        { label: "持续工作流", value: "continuous" },
      ],
    },
  },
  {
    key: "status",
    name: "状态",
    type: "select",
    labelWidth: "100px",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "已完成", value: "completed" },
        { label: "失败", value: "failed" },
        { label: "已停止", value: "stopped" },
      ],
    },
  },
  {
    key: "start_date",
    name: "开始日期",
    type: "date",
    labelWidth: "100px",
    params: {
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
    },
  },
  {
    key: "end_date",
    name: "结束日期",
    type: "date",
    labelWidth: "100px",
    params: {
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
    },
  },
];

// 获取历史状态标签
const getHistoryStatusTag = (status: string) => {
  const statusMap: Record<string, any> = {
    completed: { text: "已完成", type: "success" },
    failed: { text: "失败", type: "danger" },
    stopped: { text: "已停止", type: "warning" },
    running: { text: "运行中", type: "success" },
    processing: { text: "处理中", type: "warning" },
  };
  return statusMap[status] || { text: status, type: "info" };
};

// 获取工作流类型标签
const getWorkflowTypeTag = (type: string) => {
  const typeMap: Record<string, any> = {
    batch: { text: "批量", type: "primary" },
    continuous: { text: "持续", type: "success" },
    verification: { text: "验证", type: "warning" },
  };
  return typeMap[type] || { text: type, type: "info" };
};

// 格式化时长
const formatDuration = (seconds: number) => {
  if (!seconds) return "-";
  if (seconds < 60) return `${seconds.toFixed(1)}秒`;
  if (seconds < 3600) return `${(seconds / 60).toFixed(1)}分钟`;
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${hours}小时${minutes}分钟`;
};

const historyColumns = ref<TableColumn[]>([
  {
    label: "工作流ID",
    prop: "workflow_id",
    minWidth: 180,
    show: true,
  },
  {
    label: "类型",
    prop: "workflow_type",
    width: 100,
    show: true,
    render: (row) => {
      const typeInfo = getWorkflowTypeTag(row.workflow_type);
      return h(ElTag, { type: typeInfo.type, size: "small" }, typeInfo.text);
    },
  },
  {
    label: "状态",
    prop: "status",
    width: 100,
    show: true,
    render: (row) => {
      const statusInfo = getHistoryStatusTag(row.status);
      return h(
        ElTag,
        { type: statusInfo.type, size: "small" },
        statusInfo.text
      );
    },
  },
  {
    label: "开始时间",
    prop: "start_time",
    width: 180,
    show: true,
  },
  {
    label: "结束时间",
    prop: "end_time",
    width: 180,
    show: true,
  },
  {
    label: "持续时间",
    prop: "duration",
    width: 120,
    show: true,
    render: (row) => {
      return h("span", {}, formatDuration(row.duration));
    },
  },
  {
    label: "处理统计",
    prop: "summary",
    minWidth: 200,
    show: true,
    render: (row) => {
      const summary = row.summary || {};
      if (row.workflow_type === "batch") {
        const parts = [];
        if (summary.intelligence_processed)
          parts.push(`情报: ${summary.intelligence_processed}`);
        if (summary.assets_matched)
          parts.push(`资产: ${summary.assets_matched}`);
        if (summary.pocs_recommended)
          parts.push(`POC: ${summary.pocs_recommended}`);
        return h("span", {}, parts.join(", ") || "-");
      } else if (row.workflow_type === "continuous") {
        const parts = [];
        if (summary.total_processed)
          parts.push(`已处理: ${summary.total_processed}`);
        if (summary.last_processing_stats?.intelligence_processed)
          parts.push(
            `最新: ${summary.last_processing_stats.intelligence_processed}情报`
          );
        return h("span", {}, parts.join(", ") || "-");
      }
      return h("span", {}, "-");
    },
  },
  {
    label: "触发者",
    prop: "triggered_by",
    width: 100,
    show: true,
  },
  {
    label: "错误信息",
    prop: "error_message",
    minWidth: 200,
    show: true,
    render: (row) => {
      if (row.error_message) {
        return h("span", { style: "color: #f56c6c" }, row.error_message);
      }
      return h("span", { style: "color: #909399" }, "-");
    },
  },
]);

// 格式化时间显示
const formatTimeAgo = (timeStr: string | null) => {
  if (!timeStr) return "-";
  const time = new Date(timeStr);
  const now = new Date();
  const diffMs = now.getTime() - time.getTime();
  const diffMins = Math.floor(diffMs / 60000);

  if (diffMins < 1) return "刚刚";
  if (diffMins < 60) return `${diffMins}分钟前`;
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours}小时前`;
  const diffDays = Math.floor(diffHours / 24);
  return `${diffDays}天前`;
};

// 获取状态标签
const getStatusTag = (status: string) => {
  const statusMap: Record<string, any> = {
    running: { text: "🟢 运行中", type: "success", emoji: "🟢" },
    processing: { text: "🟡 处理中", type: "warning", emoji: "🟡" },
    idle: { text: "⏸️ 空闲", type: "info", emoji: "⏸️" },
    stopped: { text: "🔴 已停止", type: "danger", emoji: "🔴" },
    unknown: { text: "🟡 未知", type: "info", emoji: "🟡" },
  };
  return statusMap[status] || { text: status, type: "info", emoji: "⚪" };
};

// 获取工作流状态数据
const fetchWorkflowData = async () => {
  loading.value = true;
  try {
    const statusRes = await getWorkflowStatus();
    // 更新工作流状态数据（适配新的数据结构：data.workflows）
    if (statusRes?.data) {
      workflowStatusData.value = statusRes.data;
    }
  } catch (error) {
    ElMessage.error("获取工作流状态失败");
    console.error("API调用失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取工作流历史列表
const fetchWorkflowHistory = async (values?: any) => {
  historyLoading.value = true;
  try {
    const params: any = {
      page: historyPagination.currentPage,
      page_size: historyPagination.pageSize,
      ...values,
    };

    const { data } = await getWorkflowHistory(params);
    if (data) {
      workflowHistoryList.value = data.workflows || [];
      historyPagination.total = data.total || 0;
    }
  } catch (error) {
    ElMessage.error("获取工作流历史失败");
    console.error("API调用失败:", error);
  } finally {
    historyLoading.value = false;
  }
};

const handleHistorySearch = (values: any) => {
  historyPagination.currentPage = 1;
  fetchWorkflowHistory(values);
};

const handleHistoryReset = () => {
  historySearchFormRef.value?.resetFields();
  Object.assign(historySearchForm, {
    workflow_type: "",
    status: "",
    start_date: "",
    end_date: "",
  });
  historyPagination.currentPage = 1;
  fetchWorkflowHistory();
};

const handleHistoryPageChange = (page: number) => {
  historyPagination.currentPage = page;
  fetchWorkflowHistory();
};

const handleHistorySizeChange = (size: number) => {
  historyPagination.pageSize = size;
  historyPagination.currentPage = 1;
  fetchWorkflowHistory();
};

// 启动持续工作流
const handleStartContinuous = async () => {
  try {
    await startWorkflow({
      type: "continuous",
      force_rescan: false,
    });
    ElMessage.success("持续工作流启动成功");
    fetchWorkflowData();
  } catch (error) {
    ElMessage.error("启动工作流失败");
  }
};

// 手动触发批量处理
const handleManualBatch = async () => {
  ElMessageBox.prompt(
    "请输入要处理的情报ID（用逗号分隔）",
    "手动触发批量处理",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\d+(\s*,\s*\d+)*$/,
      inputErrorMessage: "请输入有效的情报ID，用逗号分隔",
      inputType: "textarea",
      inputPlaceholder: "请输入情报ID，用逗号分隔",
    }
  )
    .then(({ value }) => {
      const intelligenceIds = value
        .split(",")
        .map((id) => parseInt(id.trim()))
        .filter((id) => !isNaN(id));

      return startWorkflow({
        type: "batch",
        intelligence_ids: intelligenceIds,
        force_rescan: true,
      });
    })
    .then(() => {
      ElMessage.success("批量处理启动成功");
      fetchWorkflowData();
    })
    .catch(() => {
      // 用户取消或出错
    });
};

// 停止工作流
const handleStopWorkflow = (workflowType?: string) => {
  const typeText =
    workflowType === "continuous"
      ? "持续工作流"
      : workflowType === "batch"
      ? "批量处理"
      : workflowType === "verification"
      ? "验证扫描"
      : "工作流";

  ElMessageBox.confirm(`确定要停止${typeText}吗？`, "停止确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await stopWorkflow({
        workflow_type: workflowType,
      });
      ElMessage.success(`${typeText}已停止`);
      fetchWorkflowData();
    } catch (error) {
      ElMessage.error("停止工作流失败");
    }
  });
};

let refreshTimer: any = null;

onMounted(() => {
  fetchWorkflowData();
  fetchWorkflowHistory();
  // 每30秒自动刷新工作流状态
  refreshTimer = setInterval(() => {
    fetchWorkflowData();
  }, 30000);
});

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<template>
  <div v-loading="loading">
    <!-- 📊 工作流状态概览（根据MD文档设计） -->
    <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <span>📊 工作流状态概览</span>
      </template>
      <div
        style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px"
      >
        <!-- 持续工作流 -->
        <el-card shadow="hover">
          <div style="text-align: center">
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px">
              持续工作流
            </div>
            <el-tag
              :type="getStatusTag(workflowOverview.continuous.status).type"
              size="large"
              style="margin-bottom: 12px"
            >
              {{ getStatusTag(workflowOverview.continuous.status).text }}
            </el-tag>
            <div style="font-size: 12px; color: #666; margin-bottom: 4px">
              已处理: {{ workflowOverview.continuous.total_processed }}个
            </div>
            <div style="font-size: 12px; color: #666">
              上次: {{ formatTimeAgo(workflowOverview.continuous.last_check) }}
            </div>
          </div>
        </el-card>

        <!-- 批量处理 -->
        <el-card shadow="hover">
          <div style="text-align: center">
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px">
              批量处理
            </div>
            <el-tag
              :type="getStatusTag(workflowOverview.batch.status).type"
              size="large"
              style="margin-bottom: 12px"
            >
              {{ getStatusTag(workflowOverview.batch.status).text }}
            </el-tag>
            <div style="font-size: 12px; color: #666; margin-bottom: 4px">
              已处理: {{ workflowOverview.batch.total_processed }}个
            </div>
            <div style="font-size: 12px; color: #666">
              待处理: {{ workflowOverview.batch.pending }}个
            </div>
          </div>
        </el-card>

        <!-- 验证扫描 -->
        <el-card shadow="hover">
          <div style="text-align: center">
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px">
              验证扫描
            </div>
            <el-tag
              :type="getStatusTag(workflowOverview.verification.status).type"
              size="large"
              style="margin-bottom: 12px"
            >
              {{ getStatusTag(workflowOverview.verification.status).text }}
            </el-tag>
            <div style="font-size: 12px; color: #666; margin-bottom: 4px">
              已处理: {{ workflowOverview.verification.total_processed }}个
            </div>
            <div style="font-size: 12px; color: #666">
              队列: {{ workflowOverview.verification.queue }}个
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 🔄 工作流操作区（根据MD文档设计） -->
    <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <span>🔄 工作流操作区</span>
      </template>
      <div style="display: flex; gap: 12px; flex-wrap: wrap">
        <el-button
          type="success"
          @click="handleStartContinuous"
          :disabled="workflowOverview.continuous.status === 'running'"
        >
          启动持续工作流
        </el-button>
        <el-button
          type="danger"
          @click="handleStopWorkflow('continuous')"
          :disabled="workflowOverview.continuous.status !== 'running'"
        >
          停止工作流
        </el-button>
        <el-button type="warning" @click="handleManualBatch">
          手动触发批量处理
        </el-button>
        <el-button type="primary" @click="fetchWorkflowData">
          刷新状态
        </el-button>
      </div>
    </el-card>

    <!-- 📜 工作流历史记录（根据MD文档设计） -->
    <el-card shadow="hover">
      <template #header>
        <span>📜 工作流历史记录</span>
      </template>

      <!-- 搜索表单 -->
      <el-card shadow="never" style="margin-bottom: 10px">
        <DynamicForm
          ref="historySearchFormRef"
          v-model="historySearchForm"
          :form-config="historySearchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleHistorySearch"
          @reset="handleHistoryReset"
        />
      </el-card>

      <!-- 历史列表 -->
      <DynamicTable
        :columns="historyColumns"
        :data="workflowHistoryList"
        :loading="historyLoading"
        :pagination="historyPagination"
        @current-page-change="handleHistoryPageChange"
        @size-change="handleHistorySizeChange"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
